import { useState, useEffect } from "react";
import {
  Input,
  Dropdown,
  message,
  MenuProps,
  Avatar
} from "antd";
import { useParams, NavLink, useNavigate } from "react-router-dom";
import {
  changeFriendCommend,
  deleteFriends,
  getFriendDetil,
} from "@/api/xhr/friends";
import { getStoreItem } from "@/util/storage";
import {
  EllipsisOutlined,
  ManOutlined,
  WomanOutlined,
  CommentOutlined,
  PhoneOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import VoiceCall from "../../message/commponents/VoiceCall";
import socketInstance from "@/api/socket";
import { MessageType } from "@/api/type/messageType";
import CallSoundManager from "@/util/callSound";

type FriendDetil = {
  id: number;
  userAvatar: string;
  userName: string;
  userMail: string;
  userSex: string;
  userSignature: string | null;
  commendName: string | null;
  messageId?: number;
};

const items: MenuProps["items"] = [
  {
    key: "delete",
    danger: true,
    label: "删除好友",
    icon: <DeleteOutlined />
  }
];

const FriendsDetil = () => {
  const { friendsId } = useParams();
  const navigate = useNavigate();
  const userinfo = JSON.parse(getStoreItem("userinfo") || "{}");
  const ItemStyle = "w-80 p-3 pb-5 border-b-[1px] border-dashed flex";
  
  const [data, setdata] = useState<FriendDetil>({} as FriendDetil);
  const [commendName, setcommendName] = useState<string>("");
  const [voiceCallVisible, setVoiceCallVisible] = useState(false);
  const [incomingCall, setIncomingCall] = useState(false);

  useEffect(() => {
    GetUserDetil();
  }, [friendsId]);

  // 监听来电请求
  useEffect(() => {
    const socket = socketInstance.socket;
    if (socket && data.id) {
      // 监听通话请求
      socket.on(MessageType.VOICECALL_REQUEST, (callData) => {
        if (callData.from === data.id) {
          // 播放来电铃声
          CallSoundManager.getInstance().playRingtone();
          setIncomingCall(true);
          setVoiceCallVisible(true);
        }
      });

      // 监听通话错误
      socket.on("callError", (errorData) => {
        message.error(errorData.message || "通话请求失败");
        // 停止铃声
        CallSoundManager.getInstance().stopRingtone();
        setVoiceCallVisible(false);
      });

      return () => {
        socket.off(MessageType.VOICECALL_REQUEST);
        socket.off("callError");
        // 确保清理铃声
        CallSoundManager.getInstance().stopRingtone();
      };
    }
  }, [data.id, data.userName]);

  async function handelBlur() {
    if (commendName === data.commendName) {
      return;
    }
    const res = await changeFriendCommend({
      commendName,
      userId: userinfo.id,
      friendUserId: data.id
    });
    if (res.statusCode === 200) {
      GetUserDetil();
    }
  }

  async function GetUserDetil() {
    const userId = JSON.parse(getStoreItem("userinfo") || "{}")?.id;
    const friendUserId = Number(friendsId);
    if (userId) {
      const datainfo = await getFriendDetil({ userId, friendUserId });
      setdata(datainfo.data);
      setcommendName(datainfo.data.commendName || "");
    }
  }

  const onClick: MenuProps["onClick"] = async ({ key }) => {
    let res;
    switch (key) {
      case "delete":
        res = await deleteFriends({
          userId: userinfo.id,
          friendUserId: data.id
        });
        if (res.statusCode === 200) {
          navigate(-1);
          message.success("删除成功");
        }
        break;
      default:
        break;
    }
  };

  // 发起语音通话
  const startVoiceCall = () => {
    const socket = socketInstance.socket;
    
    if (!socket) {
      message.error("网络连接已断开，请刷新页面后重试");
      return;
    }
    
    if (!userinfo) {
      message.error("登录信息已失效，请重新登录");
      return;
    }
    
    // 检查麦克风权限
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(() => {
        // 发送通话请求
        socket.emit(MessageType.VOICECALL_REQUEST, {
          to: data.id,
          from: userinfo.id,
          username: userinfo.userName
        });
        
        // 显示正在呼叫对方的通话界面
        setIncomingCall(false); // 这是主动呼叫，而非来电
        setVoiceCallVisible(true);
        
        message.info("正在等待对方接受通话...");
      })
      .catch((err) => {
        console.error("麦克风访问错误:", err);
        if (err.name === "NotAllowedError" || err.name === "PermissionDeniedError") {
          message.error("麦克风权限被拒绝，请允许浏览器访问麦克风");
        } else if (err.name === "NotFoundError" || err.name === "DevicesNotFoundError") {
          message.error("未检测到麦克风设备，请确认麦克风已连接");
        } else if (err.name === "NotReadableError" || err.name === "TrackStartError") {
          message.error("麦克风被其他应用占用，请关闭其他使用麦克风的应用");
        } else {
          message.error(`无法访问麦克风: ${err.message}`);
        }
      });
  };

  // 关闭语音通话
  const closeVoiceCall = () => {
    // 停止铃声
    CallSoundManager.getInstance().stopRingtone();
    setVoiceCallVisible(false);
    setIncomingCall(false);
  };

  return (
    <>
      <div className="h-full w-full flex flex-col bg-white p-10 items-center ">
        <div className={ItemStyle}>
          <Avatar
            shape="square"
            src={data.userAvatar}
            className="h-[58px] w-[58px] mr-2"
          />
          <div className="flex-1">
            <div className="flex justify-between">
              <div>
                <span className="text-lg mr-1">
                  {data.commendName ? data.commendName : data.userName}
                </span>
                {Number(data.userSex) === 1 ? (
                  <ManOutlined
                    twoToneColor="#52c41a"
                    className="text-xs text-sky-500"
                  />
                ) : (
                  <WomanOutlined
                    twoToneColor="#52c41a"
                    className="text-xs text-pink-400"
                  />
                )}
              </div>
              <Dropdown menu={{ items, onClick }} placement="bottom">
                <EllipsisOutlined />
              </Dropdown>
            </div>
            <div className="flex text-[12px] mt-[2px]">
              <span>邮箱📮：</span>
              <span className="text-gray-300">{data.userMail}</span>
            </div>
          </div>
        </div>
        <div className={ItemStyle + " flex-col"}>
          <div className="flex mt-2 justify-center items-center">
            <div className="w-16 text-[14px] text-gray-400">备注：</div>
            <Input
              placeholder="添加备注名"
              variant="borderless"
              value={commendName}
              onBlur={handelBlur}
              onChange={e => setcommendName(e.target.value)}
            />
          </div>
        </div>
        <div className="w-80 p-3 flex mt-1 justify-start items-center">
          <div className="flex w-full items-center">
            <div className="text-[14px] ml-[6px] mr-2 text-gray-400">
              个性签名✍️:{" "}
            </div>
          </div>
          
          <div className="text-[14px] w-full mt-1">
            {data.userSignature ? (
              data.userSignature
            ) : (
              <span className="text-gray-400">-</span>
            )}
          </div>
        </div>
        <div className="w-80 p-3 py-8 flex justify-around">
          {data.messageId && (
            <NavLink to={`/home/message/detail/friend-${data.messageId}`}>
              <div className="text-[12px] text-[#8ecafe] cursor-pointer ">
                <CommentOutlined className="text-2xl mb-2" />
                <div>发消息</div>
              </div>
            </NavLink>
          )}

          <div
            className="text-[12px] text-[#8ecafe] cursor-pointer"
            onClick={startVoiceCall}
          >
            <PhoneOutlined className="text-2xl mb-2" />
            <div>打电话</div>
          </div>
        </div>
      </div>

      {/* 语音通话组件 */}
      {voiceCallVisible && (
        <VoiceCall
          visible={voiceCallVisible}
          onClose={closeVoiceCall}
          friendId={data.id}
          friendName={data.userName}
          friendAvatar={data.userAvatar}
          isIncoming={incomingCall}
        />
      )}
    </>
  );
};

export default FriendsDetil;
